#include<iostream>
#include<string>
#include<vector>
#include<fstream>
#include<sys/stat.h>
#include"../source/server.hpp"
size_t Split(const std::string&src,const std::string&sep,std::vector<std::string>*arry){
    int count=0;
    int offset=0;
    size_t pos=src.find(sep,offset);
    while(pos!=std::string::npos){
        if(offset<pos)
        arry->push_back(src.substr(offset,pos-offset));
        offset=pos+sep.size();
        pos=src.find(sep,offset);
        count++;
    }
     if(offset<src.size())
    arry->push_back(src.substr(offset));
    return arry->size();
}
static bool ReadFile(std::string&filename,std::string&buffer){
    std::ifstream ifs(filename.c_str(),std::ios::binary);
    if(!ifs.is_open()){
        ERR_LOG("open file failed:%s",filename.c_str());
        return false;
    }
    size_t fsize=0;
    ifs.seekg(0,std::ios::end);
    fsize=ifs.tellg();
    ifs.seekg(0,std::ios::beg);
    std::string content;
    content.resize(fsize);
    ifs.read(&content[0],fsize);
    if(ifs.good()==false){
        ERR_LOG("read file failed:%s",filename.c_str());
        ifs.close();
        return false;
    }
    buffer=content;
    return true;
}
static bool WriteFile(const std::string&filename,std::string&buf){
    std::ofstream ofs(filename.c_str(),std::ios::binary|std::ios::trunc);
    if(!ofs.is_open()){
        ERR_LOG("open file failed:%s",filename.c_str());
        return false;
    }
    ofs.write(buf.c_str(),buf.size());
    if(ofs.good()==false){
        ERR_LOG("write file failed:%s",filename.c_str());
        ofs.close();
        return false;
    }
    return true;
}
static std::string UrlEncode(const std::string&url,bool  convert_space_to_plus){
    std::string result;
    for(auto c:url)
    {
        if(c=='.'||c=='-'||c=='_'||c=='~'||('0'<=c&&c<='9')||('a'<=c&&c<='z')||('A'<=c&&c<='Z')){
            result+=c;
        }
        else if(c==' '&&convert_space_to_plus){
            result+='+';
        }
        else{
            char tmp[4]={0};
            sprintf(tmp,"%%%02X",(unsigned char)c);
            result+=tmp;
        }
    }
    return result;
}
int HEXTOI(char c){
    if(c>='0'&&c<='9')
        return c-'0';
    if(c>='a'&&c<='f')
        return c-'a'+10;
    if(c>='A'&&c<='F')
        return c-'A'+10;
    return -1;
}
static std::string UrlDecode(std::string&url,bool convert_plus_to_space){
    std::string result;
    for(auto i=0;i<url.size();i++){
        if(url[i]=='%'){
            if(i+2>=url.size()){
                ERR_LOG("url decode failed:%s",url.c_str());
                return "";
            }
            char tmp=HEXTOI(url[i+1])*16+HEXTOI(url[i+2]);
            result+=tmp;
            i+=2;
        }
        else if(url[i]=='+'&&convert_plus_to_space){
            result+=' ';
        }
        else{
            result+=url[i];
        }
    }
    return result;
}
static std::string StatuDesc(int status){
    std::unordered_map<int,std::string> _status_map={{100, "Continue"},
    {101, "Switching Protocol"},
    {102, "Processing"},
    {103, "Early Hints"},
    {200, "OK"},
    {201, "Created"},
    {202, "Accepted"},
    {203, "Non-Authoritative Information"},
    {204, "No Content"},
    {205, "Reset Content"},
    {206, "Partial Content"},
    {207, "Multi-Status"},
    {208, "Already Reported"},
    {226, "IM Used"},
    {300, "Multiple Choice"},
    {301, "Moved Permanently"},
    {302, "Found"},
    {303, "See Other"},
    {304, "Not Modified"},
    {305, "Use Proxy"},
    {306, "unused"},
    {307, "Temporary Redirect"},
    {308, "Permanent Redirect"},
    {400, "Bad Request"},
    {401, "Unauthorized"},
    {402, "Payment Required"},
    {403, "Forbidden"},
    {404, "Not Found"},
    {405, "Method Not Allowed"},
    {406, "Not Acceptable"},
    {407, "Proxy Authentication Required"},
    {408, "Request Timeout"},
    {409, "Conflict"},
    {410, "Gone"},
    {411, "Length Required"},
    {412, "Precondition Failed"},
    {413, "Payload Too Large"},
    {414, "URI Too Long"},
    {415, "Unsupported Media Type"},
    {416, "Range Not Satisfiable"},
    {417, "Expectation Failed"},
    {418, "I'm a teapot"},
    {421, "Misdirected Request"},
    {422, "Unprocessable Entity"},
    {423, "Locked"},
    {424, "Failed Dependency"},
    {425, "Too Early"},
    {426, "Upgrade Required"},
    {428, "Precondition Required"},
    {429, "Too Many Requests"},
    {431, "Request Header Fields Too Large"},
    {451, "Unavailable For Legal Reasons"},
    {501, "Not Implemented"},
    {502, "Bad Gateway"},
    {503, "Service Unavailable"},
    {504, "Gateway Timeout"},
    {505, "HTTP Version Not Supported"},
    {506, "Variant Also Negotiates"},
    {507, "Insufficient Storage"},
    {508, "Loop Detected"},
    {510, "Not Extended"},
    {511, "Network Authentication Required"}
};
auto it=_status_map.find(status);
if(it!=_status_map.end()){
    return it->second;
}
return "UnKonwn Status";
}
static std::string ExtMime(std::string&filename){
    std::unordered_map<std::string,std::string> _ext_mime={{".aac", "audio/aac"},
    {".abw", "application/x-abiword"},
    {".arc", "application/x-freearc"},
    {".avi", "video/x-msvideo"},
    {".azw", "application/vnd.amazon.ebook"},
    {".bin", "application/octet-stream"},
    {".bmp", "image/bmp"},
    {".bz", "application/x-bzip"},
    {".bz2", "application/x-bzip2"},
    {".csh", "application/x-csh"},
    {".css", "text/css"},
    {".csv", "text/csv"},
    {".doc", "application/msword"},
    {".docx", "application/vnd.openxmlformats-officedocument.wordprocessingml.document"},
    {".eot", "application/vnd.ms-fontobject"},
    {".epub", "application/epub+zip"},
    {".gif", "image/gif"},
    {".htm", "text/html"},
    {".html", "text/html"},
    {".ico", "image/vnd.microsoft.icon"},
    {".ics", "text/calendar"},
    {".jar", "application/java-archive"},
    {".jpeg", "image/jpeg"},
    {".jpg", "image/jpeg"},
    {".js", "text/javascript"},
    {".json", "application/json"},
    {".jsonld", "application/ld+json"},
    {".mid", "audio/midi"},
    {".midi", "audio/x-midi"},
    {".mjs", "text/javascript"},
    {".mp3", "audio/mpeg"},
    {".mpeg", "video/mpeg"},
    {".mpkg", "application/vnd.apple.installer+xml"},
    {".odp", "application/vnd.oasis.opendocument.presentation"},
    {".ods", "application/vnd.oasis.opendocument.spreadsheet"},
    {".odt", "application/vnd.oasis.opendocument.text"},
    {".oga", "audio/ogg"},
    {".ogv", "video/ogg"},
    {".ogx", "application/ogg"},
    {".otf", "font/otf"},
    {".png", "image/png"},
    {".pdf", "application/pdf"},
    {".ppt", "application/vnd.ms-powerpoint"},
    {".pptx", "application/vnd.openxmlformats-officedocument.presentationml.presentation"},
    {".rar", "application/x-rar-compressed"},
    {".rtf", "application/rtf"},
    {".sh", "application/x-sh"},
    {".svg", "image/svg+xml"},
    {".swf", "application/x-shockwave-flash"},
    {".tar", "application/x-tar"},
    {".tif", "image/tiff"},
    {".tiff", "image/tiff"},
    {".ttf", "font/ttf"},
    {".txt", "text/plain"},
    {".vsd", "application/vnd.visio"},
    {".wav", "audio/wav"},
    {".weba", "audio/webm"},
    {".webm", "video/webm"},
    {".webp", "image/webp"},
    {".woff", "font/woff"},
    {".woff2", "font/woff2"},
    {".xhtml", "application/xhtml+xml"},
    {".xls", "application/vnd.ms-excel"},
    {".xlsx", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"},
    {".xml", "application/xml"},
    {".xul", "application/vnd.mozilla.xul+xml"},
    {".zip", "application/zip"},
    {".3gp", "video/3gpp"},
    {".3g2", "video/3gpp2"},
    {".7z", "application/x-7z-compressed"}
    };
    auto it=_ext_mime.find(filename.substr(filename.rfind('.')));
    if(it!=_ext_mime.end())
        return it->second;
    return "application/octet-stream";//二进制流文件
}
static bool IsDirectory(std::string&filename){
    struct stat st;
    int ret=stat(filename.c_str(),&st);
    if(ret<0){
        return false;
    }
    return S_ISDIR(st.st_mode);
}
//判断一个文件是不是普通文件
static bool IsRegular(std::string&filename){
    struct stat st;
    int ret=stat(filename.c_str(),&st);
    if(ret<0){
        return false;
    }
    return S_ISREG(st.st_mode);
}
static bool ValidPath(std::string&path){
    //按照/进行路径分割，计算路径深度，如果最低层次低于0，则认为是非法路径
    std::vector<std::string> arry;
    Split(path,"/",&arry);
    int depth=0;
    for(auto&s:arry){
        if(s==".."){
            depth--;
            if(depth<0)
                return false;
        }
        else if(s!=".")
            depth++;
        }
        return true;
}
int main(){
    std::string path="././../";
    std::cout<<ValidPath(path)<<std::endl;
    path="/root/././../http-v1/example/test.cc/";
    std::cout<<ValidPath(path)<<std::endl;
    path="/root/http-v1/example/test.cc/../../";
    std::cout<<ValidPath(path)<<std::endl;
    path="/root/http-v1/example/test.cc/../../../";
    std::cout<<ValidPath(path)<<std::endl;
    path="/root/../http-v1/example/test.cc/../../../../../";
    std::cout<<ValidPath(path)<<std::endl;
//     std::string filename="./";
// std::cout<<IsDirectory(filename)<<std::endl;
// std::cout<<IsRegular(filename)<<std::endl;
// filename="./timewheel.cpp";
// std::cout<<IsDirectory(filename)<<std::endl;
// std::cout<<IsRegular(filename)<<std::endl;
// std::string buffer;
//  std::string filename="./timewheel.cpp";
//     bool ret=ReadFile(filename,buffer);

//     std::string filename1="./tt.cc";
//     WriteFile(filename1,buffer);
// std::string url="http://www.baidu.com/s?wd=hello world";
// std::string encode_url=UrlEncode(url,true);
// std::string decode_url=UrlDecode(encode_url,true);
// std::cout<<url<<std::endl;
// std::cout<<encode_url<<std::endl;
// std::cout<<decode_url<<std::endl;
// int code=200;
// std::cout<<StatuDesc(code)<<std::endl;
// code=302;
// std::cout<<StatuDesc(code)<<std::endl;
// code=404;
// std::cout<<StatuDesc(code)<<std::endl;
// code=800;
// std::cout<<StatuDesc(code)<<std::endl;
// std::string filename="test.txt";
// std::cout<<ExtMime(filename)<<std::endl;
// filename="test.cpp";
// std::cout<<ExtMime(filename)<<std::endl;
// filename="test.jpg";
// std::cout<<ExtMime(filename)<<std::endl;
// filename="test.xxx";
// std::cout<<ExtMime(filename)<<std::endl;
return 0;
}